package helper

import (
	"net/http"
	"net/url"
	"github.com/tencentyun/cos-go-sdk-v5"
	"path"
	"context"
	"strconv"
	"bytes"
	"strings"
	"io"
)

// c.Jwt.SignerKey
// 上传文件到腾讯云
func CosUpload(r *http.Request) (string, error) {
	u, _ := url.Parse(c.Tencent.BucketUrl)
	b := &cos.BaseURL{
		BucketURL: u,
	}

	client := cos.NewClient(b, &http.Client {
		Transport: &cos.AuthorizationTransport{
			SecretID: c.Tencent.SecretId,
			SecretKey: c.Tencent.SecretKey,
		},
	})

	file, fileHeader, err := r.FormFile("file")
	// 上传的文件夹
	key := "clouddisk/" + UUID() + path.Ext(fileHeader.Filename)

	_, err = client.Object.Put(
		context.Background(), key, file, nil,
	)

	if err != nil {
		panic(err)
	}

	return c.Tencent.BucketUrl + "/" + key, nil
}

// 分片上传完成
func CosPartUploadComplete(key, uploadId string, co []cos.Object) error {
	u, _ := url.Parse(c.Tencent.BucketUrl)
	b := &cos.BaseURL{
		BucketURL: u,
	}

	client := cos.NewClient(b, &http.Client {
		Transport: &cos.AuthorizationTransport{
			SecretID: c.Tencent.SecretId,
			SecretKey: c.Tencent.SecretKey,
		},
	})

	opt := &cos.CompleteMultipartUploadOptions{}
	opt.Parts = append(opt.Parts, co...)

	_, _, err := client.Object.CompleteMultipartUpload(
		context.Background(), key, uploadId, opt,
	)

	return err
}

func CosInitPart(ext string) (string, string, error) {
	u, _ := url.Parse(c.Tencent.BucketUrl)
	b := &cos.BaseURL{
		BucketURL: u,
	}

	client := cos.NewClient(b, &http.Client {
		Transport: &cos.AuthorizationTransport{
			SecretID: c.Tencent.SecretId,
			SecretKey: c.Tencent.SecretKey,
		},
	})
	// tencent远程文件路径
	key := "clouddisk/" + UUID() + ext

	v, _, err := client.Object.InitiateMultipartUpload(
		context.Background(), key, nil,
	)
	if err != nil {
		return "", "", err
	}

	return key, v.UploadID, nil
}

func CosPartUpload(r *http.Request) (string, error) {
	u, _ := url.Parse(c.Tencent.BucketUrl)
	b := &cos.BaseURL{
		BucketURL: u,
	}

	client := cos.NewClient(b, &http.Client {
		Transport: &cos.AuthorizationTransport{
			SecretID: c.Tencent.SecretId,
			SecretKey: c.Tencent.SecretKey,
		},
	})
	// 获取上传路径
	key := r.PostForm.Get("key")
	uploadID := r.PostForm.Get("upload_id")
	partNumber, err := strconv.Atoi(r.PostForm.Get("part_number"))
	if err != nil {
		return "", err
	}

	f, _, err := r.FormFile("file")
	if err != nil {
		return "", err
	}

	buf := bytes.NewBuffer(nil)
	io.Copy(buf, f)

	// options
	resp, err := client.Object.UploadPart(
		context.Background(),key,uploadID,partNumber,bytes.NewReader(buf.Bytes()), nil,
	)

	if err != nil {
		return "", err
	}

	return strings.Trim(resp.Header.Get("ETag"), "\""), nil

}